// ==UserScript==
// @name         58同城厂房信息抓取
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  抓取58同城厂房信息
// @author       George Cai
// @match        https://sh.58.com/fangchan/*
// @grant        GM_download
// @grant        GM_saveTab
// @grant        GM_xmlhttpRequest
// @connect      *
// ==/UserScript==

(function() {
    'use strict';

    // 在 createTriggerButton 函数之前添加解除复制限制的函数
    function removeAntiCopy() {
        // 移除所有元素的复制限制
        const removeLimit = () => {
            document.querySelectorAll('*').forEach(el => {
                el.style.userSelect = 'text';  // 允许文本选择
                el.oncontextmenu = null;       // 允许右键
                el.onselectstart = null;       // 允许选择
                el.onselect = null;
                el.oncopy = null;              // 允许复制
                el.oncut = null;               // 允许剪切
                el.onpaste = null;             // 允许粘贴
            });
            
            // 移除 body 的事件监听器
            document.body.oncopy = null;
            document.body.oncut = null;
            document.body.onselectstart = null;
            document.body.oncontextmenu = null;
            
            // 添加自定义样式
            const style = document.createElement('style');
            style.innerHTML = `
                * {
                    -webkit-user-select: text !important;
                    -moz-user-select: text !important;
                    -ms-user-select: text !important;
                    user-select: text !important;
                }
            `;
            document.head.appendChild(style);
        };

        // 立即执行一次
        removeLimit();

        // 创建一个观察器来处理动态添加的元素
        const observer = new MutationObserver(removeLimit);
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    // 立即执行移除复制限制
    removeAntiCopy();

    // 创建触发按钮
    function createTriggerButton() {
        const button = document.createElement('button');
        // 添加蜘蛛图标和文字
        button.innerHTML = `
            <span class="spider-icon">🕷️</span>
            <span class="button-text">开始抓取数据</span>
        `;
        
        // 更新按钮样式
        button.style.cssText = `
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 9999;
            width: 40px;
            height: 40px;
            padding: 8px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            overflow: hidden;
            white-space: nowrap;
            display: flex;
            align-items: center;
            justify-content: center;
        `;

        // 添加样式到head
        const style = document.createElement('style');
        style.textContent = `
            .spider-icon {
                font-size: 20px;
                display: inline-block;
                transition: all 0.3s ease;
            }
            
            .button-text {
                opacity: 0;
                width: 0;
                display: inline-block;
                margin-left: 0;
                transition: all 0.3s ease;
                overflow: hidden;
            }
            
            /* 悬停效果 */
            button:hover {
                width: 140px !important;
                background-color: #45a049 !important;
            }
            
            button:hover .spider-icon {
                margin-right: 8px;
            }
            
            button:hover .button-text {
                opacity: 1;
                width: auto;
                margin-left: 4px;
            }
        `;
        document.head.appendChild(style);

        // 添加点击事件
        button.addEventListener('click', scrapeData);
        document.body.appendChild(button);
    }

    // 创建一个函数来获取文内容，避免获取到隐藏的元素内容
    function getCleanText(element) {
        if (!element) return '';
        return element.innerText.trim();
    }

    // 主要的抓取函数
    function scrapeData() {
        let data = {
            标题: document.querySelector('.house-title h1')?.innerText.trim(),
            标签: Array.from(document.querySelectorAll('.house-update-info span'))
                      .filter(item => !item.classList.contains('up'))
                      .map(item => item.innerText.trim()),
            发布日期: document.querySelector('.house-update-info .up')?.innerText.replace('发布于','').trim(),
            价格: document.querySelector('.house_basic_title_money_num')?.innerText.trim() + document.querySelector('.house_basic_title_money_unit')?.innerText.trim(),
            平均单价: document.querySelector('.house_basic_title_money_num_second')?.innerText.trim().split('（')[0].trim(),
            建筑面积: document.querySelector('.house_basic_title_info .up')?.innerText.trim(),
            厂房类型: document.querySelectorAll('.house_basic_title_info .up')[1]?.innerText.trim(),
            厂房新旧: document.querySelectorAll('.house_basic_title_info .up')[2]?.innerText.trim(),
            区域: document.querySelector('.house_basic_title_info_2 p:first-child')?.innerText.replace(/区\s*域\s*：/,'').trim().split('-')[0].trim(),
            街道: document.querySelector('.house_basic_title_info_2 p:first-child')?.innerText.replace('区域：','').trim().split('-')[1].trim(),
            地址: document.querySelector('.house_basic_title_info_2 .address')?.innerText.trim(),
            基本信息: (() => {
                const params = {};
                document.querySelectorAll('#jichu .intro-item').forEach(item => {
                    const key = item.querySelector('.title')?.innerText.trim() || '';
                    const value = item.querySelector('.content')?.innerText.trim() || '';
                    if (key) params[key] = value;
                });
                return params;
            })(),
            内部参数: (() => {
                const params = {};
                document.querySelectorAll('.general-item.general-intro .intro-item').forEach(item => {
                    const key = item.querySelector('.title')?.innerText.trim() || '';
                    const value = item.querySelector('.content')?.innerText.trim() || '';
                    if (key) params[key] = value;
                });
                return params;
            })(),
            描述: document.querySelector('.des-item .detail')?.innerText.trim() ||
                  document.querySelector('.general-item.general-miaoshu .detail')?.innerText.trim(),
            图集: (() => {
                const images = Array.from(document.querySelectorAll('.general-pic-list img'));
                return {
                    count: images.length,
                    photos: images.map(img => img.src)
                };
            })()
        };

        // 创建结果显示面板
        let panel = document.createElement('div');
        panel.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            max-height: 80vh;
            overflow-y: auto;
            z-index: 9999;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        `;

        // 添加复制按钮
        let copyButton = document.createElement('button');
        copyButton.innerText = '复制数据';
        copyButton.style.cssText = `
            padding: 8px 16px;
            background-color: #008CBA;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-bottom: 10px;
        `;

        copyButton.onclick = () => {
            navigator.clipboard.writeText(JSON.stringify(data, null, 2));
            alert('数据已复制到剪贴板！');
        };
        panel.appendChild(copyButton);

        // 在创建复制按钮后，添加下载按钮
        let downloadButton = document.createElement('button');
        downloadButton.innerText = '下载JSON';
        downloadButton.style.cssText = `
            padding: 8px 16px;
            background-color: #673AB7;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
            margin-bottom: 10px;
        `;

        downloadButton.onclick = () => {
            const fileName = `${data.标题 || '58同城厂房'}_${new Date().toLocaleString().replace(/[\/\s:]/g, '_')}.json`;
            const jsonString = JSON.stringify(data, null, 2);

            try {
                // 使用 Data URL 方式
                const dataUrl = 'data:application/json;charset=utf-8,' + encodeURIComponent(jsonString);

                GM_download({
                    url: dataUrl,
                    name: fileName,
                    saveAs: true,
                    onerror: (error) => {
                        console.error('下载失败，尝试备用方案:', error);
                        // 备用方案1：使用 a 标签 + Data URL
                        const a = document.createElement('a');
                        a.href = dataUrl;
                        a.download = fileName;
                        a.style.display = 'none';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    }
                });
            } catch (error) {
                console.error('主下载方案失败，尝试备用方案2:', error);
                // 备用方案2：使用 Blob
                try {
                    const blob = new Blob([jsonString], { type: 'application/json' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    a.style.display = 'none';
                    document.body.appendChild(a);
                    a.click();
                    URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                } catch (fallbackError) {
                    console.error('所有下载方案失败:', fallbackError);
                    // 最后的备用方案：打开新标签页
                    const newTab = window.open();
                    newTab.document.write('<pre>' + jsonString + '</pre>');
                    newTab.document.close();
                    alert('下载失败，已在新标签页中打开数据，请手动保存。');
                }
            }
        };
        panel.appendChild(downloadButton);

        // 在下载JSON按钮之后，添加下载图片按钮
        let downloadImagesButton = document.createElement('button');
        downloadImagesButton.innerText = '下载图片';
        downloadImagesButton.style.cssText = `
            padding: 8px 16px;
            background-color: #FF5722;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
            margin-bottom: 10px;
        `;

        downloadImagesButton.onclick = async () => {
            const images = data.图集.photos;
            if (!images || images.length === 0) {
                alert('没有找到图片！');
                return;
            }

            // 创建进度显示元素
            const progressDiv = document.createElement('div');
            progressDiv.style.cssText = `
                margin-top: 10px;
                padding: 10px;
                background-color: #f5f5f5;
                border-radius: 4px;
            `;
            panel.insertBefore(progressDiv, pre);

            // 创建文件夹名称（使用标题和时间）
            const folderPrefix = `${data.标题 || '58同城厂房'}_${new Date().toLocaleString().replace(/[\/\s:]/g, '_')}`;

            // 下载所有图片
            for (let i = 0; i < images.length; i++) {
                const imageUrl = images[i];
                const fileName = `${folderPrefix}_图片${i + 1}.jpg`;

                progressDiv.textContent = `正在下载: ${i + 1}/${images.length} 张图片`;

                try {
                    await new Promise((resolve, reject) => {
                        GM_download({
                            url: imageUrl,
                            name: fileName,
                            onload: resolve,
                            onerror: reject
                        });

                        // 添加延迟，避免同时下载太多
                        setTimeout(resolve, 500);
                    });
                } catch (error) {
                    console.error(`图片 ${i + 1} 下载失败:`, error);
                    progressDiv.textContent += `\n图片 ${i + 1} 下载失败: ${imageUrl}`;
                }
            }

            progressDiv.textContent = `下载完成！共 ${images.length} 张图片`;

            // 3秒后移除进度显示
            setTimeout(() => {
                progressDiv.remove();
            }, 3000);
        };

        // 在下载JSON按钮后添加下载图片按钮
        panel.appendChild(downloadImagesButton);

        // 添加关闭按钮
        let closeButton = document.createElement('button');
        closeButton.innerText = '关闭';
        closeButton.style.cssText = `
            padding: 8px 16px;
            background-color: #f44336;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
            margin-bottom: 10px;
        `;

        closeButton.onclick = () => {
            panel.remove();
        };
        panel.appendChild(closeButton);

        // 显示数据
        let pre = document.createElement('pre');
        pre.style.cssText = `
            margin-top: 10px;
            white-space: pre-wrap;
            word-wrap: break-word;
            background-color: #1e1e1e;
            color: #d4d4d4;
            padding: 15px;
            border-radius: 4px;
            font-family: Consolas, Monaco, 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.5;
        `;
        pre.textContent = JSON.stringify(data, null, 2);
        panel.appendChild(pre);

        document.body.appendChild(panel);
    }

    // 页面加载完成后添加触发按钮
    window.addEventListener('load', createTriggerButton);
})();